package at.spengergasse.dao.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

// final classes koennen nicht abgeleitet werden
public final class JDBCConnectionController
{

	private static final String URL = "jdbc:derby://localhost:1527/testDB";
	private static final String USER_NAME = "onlineshop";
	private static final String PASSWORD = "geheim";

	private static Connection readOnlyConnection;
	private static Connection connection;

	// static initializer, wird executiert wenn Klasse geladen wird
	static
	{
		try
		{
			Class.forName("org.apache.derby.jdbc.ClientDriver");
			initConnection();
			initReadOnlyConnection();
		} catch (ClassNotFoundException e)
		{
			System.err.println("Konnte JDBC Treiber nicht laden!");
			System.exit(-815);
		} catch (SQLException e)
		{
			System.err.println("Konnte keine Connection aufbauen:\n" + "URL:  "
					+ URL + "\n" + "User: " + USER_NAME + "\n" + "Pwd:  "
					+ PASSWORD);
			System.exit(-4711);
		}
	}

	// private constructor verhindert instantiierung
	private JDBCConnectionController()
	{
	}

	private static void initConnection() throws SQLException
	{
		connection = DriverManager.getConnection(URL, USER_NAME, PASSWORD);
		connection.setAutoCommit(false);
	}

	private static void initReadOnlyConnection() throws SQLException
	{
		readOnlyConnection = DriverManager.getConnection(URL, USER_NAME,
				PASSWORD);
		readOnlyConnection.setReadOnly(true);
	}

	public static Connection getConnection() throws SQLException
	{
		if (connection.isClosed() || connection.isValid(100))
		{
			initConnection();
		}
		return connection;
	}

	public static Connection getReadOnlyConnection() throws SQLException
	{
		if (readOnlyConnection.isClosed())
		{
			initReadOnlyConnection();
		}
		return readOnlyConnection;
	}
}
